package com.itheima.goods.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.service.GoodsService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
@CrossOrigin
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping()
    public Result findAll() {
        List<Goods> list = goodsService.list();
        return new Result(true, StatusCode.OK, "查询成功", list);
    }

    @PostMapping()
    public Result add(@RequestBody Goods goods) {
        goodsService.save(goods);
        return new Result(true, StatusCode.OK, "添加成功");
    }

    @GetMapping("search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size) {
        Page<Goods> pages = goodsService.page(new Page<Goods>(page, size));
        PageResult<Goods> goodsPageResult = new PageResult<>();
        goodsPageResult.setTotal(pages.getTotal());
        goodsPageResult.setRows(pages.getRecords());
        return new Result(true, StatusCode.OK, "查询成功", goodsPageResult);
    }

    @PostMapping("search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size,
                           @RequestBody Map searchMap) {

        PageResult pageResult = goodsService.findPage(page, size, searchMap);

        return new Result(true, StatusCode.OK, "查询成功", pageResult);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Long id) {
        Goods goods = goodsService.getById(id);
        return new Result(true, StatusCode.OK, "查询成功", goods);
    }

    @PutMapping("/{id}")
    public Result update(@RequestBody Goods goods,
                         @PathVariable("id") Integer id) {
        LambdaQueryWrapper<Goods> wrapper = Wrappers.<Goods>lambdaQuery();
        wrapper.eq(Goods::getId, id);
        goodsService.update(goods, wrapper);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        goodsService.removeById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }

    //根据goodId找到对应数据,再扣减库存数量buyNum
    @PostMapping("/buy")
    public Result buy(@RequestParam("goodId") Long id,
                      @RequestParam("buyNum") Integer buyNum){
        return goodsService.buy(id,buyNum);
    }
}
